﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using SelfService.Helpers;
using WalkingTec.Mvvm.Core;
using SelfService.Model.Models;
using SelfService.Model;
using SelfService.Model.Interface;
using SelfService.Model.ViewModels;
using TT;
using WalkingTec.Mvvm.Core.Extensions;
using WalkingTec.Mvvm.Mvc;


namespace SelfService.Controllers
{

    [AuthorizeJwtWithCookie]
    public partial class SysPatientController
    {
        private readonly IHisUser _hisUserService;

        public SysPatientController(IHisUser hisUserService)
        {
            _hisUserService = hisUserService;
        }

        /// <summary>
        ///  查询用户
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        [ActionDescription("查询")]
        [HttpPost("GetUser")]
        public async Task<Result<SysPatient>> GetUser([FromBody] SysPatientSearcher search)
        {
            try
            {
                if (search.Uid.IsNullOrWhiteSpace() && search.IdCardNo.IsNullOrWhiteSpace() && search.IcCardNo.IsNullOrWhiteSpace())
                {
                    return new Result<SysPatient>()
                    {
                        Code = 1,
                        Message = "请至少提供一种身份凭据"
                    };
                }
                
                if (!search.IdCardNo.IsNullOrWhiteSpace())
                {
                    if (!Common.CheckIdCardNo(search.IdCardNo))
                    {
                        return new Result<SysPatient>()
                        {
                            Code = 1,
                            Message = "无效的身份证号码"
                        };
                    }
                }

                var data = await _hisUserService.GetUser(search);
                if (data.Code == 200)
                {
                    this.Logger($"查询用户信息. 请求数据:{data.Request}, 返回数据:{data.Response}", ActionLogTypesEnum.Debug);
                    SysPatient patient = await DC.Set<SysPatient>()
                        .CheckEqual(search.Uid, e => e.Uid)
                        .CheckEqual(search.IdCardNo, e => e.IdCardNo)
                        .CheckEqual(search.CardNo, e => e.CardNo)
                        .FirstOrDefaultAsync();
                    if (patient == null)
                    {
                        patient = new SysPatient();
                        patient.CopyPropertyFrom(data.Data);
                        patient.ID = Guid.NewGuid();
                        if(patient.CreateTime == new DateTime()) patient.CreateTime = DateTime.Now;
                        patient.LastTime = DateTime.Now;
                        await DC.Set<SysPatient>().AddAsync(patient);
                        await DC.SaveChangesAsync();
                    }
                    else
                    {
                        if (patient.Name.IsNullOrWhiteSpace()) patient.Name = data.Data.Name;
                        if (patient.Uid.IsNullOrWhiteSpace()) patient.Uid = search.Uid;
                        if (patient.IdCardNo.IsNullOrWhiteSpace()) patient.IdCardNo = data.Data.IdCardNo;
                        if (patient.Address.IsNullOrWhiteSpace()) patient.Address = search.Address;
                        if (!patient.IdCardNo.IsNullOrWhiteSpace()) patient.Age = Common.GetAgeByIdCardNo(patient.IdCardNo);
                        if (patient.HisCode.IsNullOrWhiteSpace()) patient.HisCode = data.Data.HisCode;
                        patient.Balance = data.Data.Balance;
                        patient.LastTime = DateTime.Now;
                        await DC.SaveChangesAsync();
                    }
                    return new Result<SysPatient>()
                    {
                        Data = patient
                    };
                }else if (data.Code == 2)
                {
                    this.Logger($"查询用户信息. 请求数据:{data.Request}, 返回数据:{data.Response}", ActionLogTypesEnum.Debug);
                    return new Result<SysPatient>()
                    {
                        Code = 2,
                        Message = "用户未建档"
                    };
                }
                else
                {
                    this.Logger($"查询用户信息失败, 请求数据:{data.Request}, 返回数据:{data.Response}", ActionLogTypesEnum.Exception);
                    return new Result<SysPatient>()
                    {
                        Code = 1,
                        Message = "查询失败"
                    };
                }
            }
            catch (Exception e)
            {
                this.Logger($"查询用户信息异常. 用户信息:{JsonSerializer.Serialize(search)}, 异常信息: {e.Message}", ActionLogTypesEnum.Exception);
                return new Result<SysPatient>()
                {
                    Code = 1,
                    Message = "未知错误, 请联系管理员!"
                };
            }
        }

        /// <summary>
        ///  通过ECode查询用户
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [ActionDescription("通过ECode查询")]
        [HttpGet("GetUserByECode/{code}")]
        public async Task<Result<SysPatient>> GetUserByECode(string code)
        {
            try
            {
                //查询客户端
                var client = await this.GetClientAsync();
                if (client == null)
                {
                    return new Result<SysPatient>()
                    {
                        Code = 1,
                        Message = "无效客户端"
                    };
                }
                code = code.Trim();
                if (code.IsNullOrWhiteSpace())
                {
                    return new Result<SysPatient>()
                    {
                        Code = 1,
                        Message = "凭据错误"
                    };
                }

                //查询操作员
                var @operator = await DC.Set<SysOperator>()
                    .Include(e => e.Group)
                    .FirstOrDefaultAsync(e => e.ClientId == client.Entity.ID && e.Group.Name == "His操作员" && e.IsEnable == CommonYesOrNo.是);
                if (@operator == null)
                {
                    return new Result<SysPatient>()
                    {
                        Code = 1,
                        Message = "操作员无效"
                    };
                }
                var data = await _hisUserService.GetUserByECode(code, client.Entity, @operator);
                if (data.Code == 200)
                {
                    this.Logger($"查询用户信息. 请求数据:{data.Request}, 返回数据:{data.Response}", ActionLogTypesEnum.Debug);
                    SysPatient patient = await DC.Set<SysPatient>()
                        .CheckEqual(data.Data.CardNo, e => e.CardNo)
                        .FirstOrDefaultAsync();
                    if (patient == null)
                    {
                        patient = new SysPatient();
                        patient.CopyPropertyFrom(data.Data);
                        patient.ID = Guid.NewGuid();
                        if (patient.CreateTime == new DateTime()) patient.CreateTime = DateTime.Now;
                        patient.LastTime = DateTime.Now;
                        await DC.Set<SysPatient>().AddAsync(patient);
                        await DC.SaveChangesAsync();
                    }
                    else
                    {
                        if (patient.Name.IsNullOrWhiteSpace() && patient.Name != data.Data.Name) patient.Name = data.Data.Name;
                        if (patient.Uid.IsNullOrWhiteSpace() && !data.Data.Uid.IsNullOrWhiteSpace()) patient.Uid = data.Data.Uid;
                        if (patient.IdCardNo.IsNullOrWhiteSpace() && !data.Data.IdCardNo.IsNullOrWhiteSpace()) patient.IdCardNo = data.Data.IdCardNo;
                        if (patient.Address.IsNullOrWhiteSpace() && !data.Data.Address.IsNullOrWhiteSpace()) patient.Address = data.Data.Address;
                        if (!patient.IdCardNo.IsNullOrWhiteSpace()) patient.Age = Common.GetAgeByIdCardNo(patient.IdCardNo);
                        patient.Balance = data.Data.Balance;
                        patient.LastTime = DateTime.Now;
                        await DC.SaveChangesAsync();
                    }
                    return new Result<SysPatient>()
                    {
                        Data = patient
                    };
                }
                else if (data.Code == 2)
                {
                    this.Logger($"查询用户信息. 请求数据:{data.Request}, 返回数据:{data.Response}", ActionLogTypesEnum.Debug);
                    return new Result<SysPatient>()
                    {
                        Code = 2,
                        Message = "用户未建档"
                    };
                }
                else
                {
                    this.Logger($"查询用户信息失败, 请求数据:{data.Request}, 返回数据:{data.Response}", ActionLogTypesEnum.Exception);
                    return new Result<SysPatient>()
                    {
                        Code = 1,
                        Message = data.Message
                    };
                }
            }
            catch (Exception e)
            {
                this.Logger($"查询用户信息异常. Code:{code}, 异常信息: {JsonSerializer.Serialize(e)}", ActionLogTypesEnum.Exception);
                return new Result<SysPatient>()
                {
                    Code = 1,
                    Message = "查询档案失败, 请稍后重试"
                };
            }
        }

        /// <summary>
        /// 创建用户
        /// </summary>
        /// <param name="post"></param>
        /// <returns></returns>
        [ActionDescription("注册")]
        [HttpPost("Reg")]
        public async Task<Result<SysPatient>> Reg([FromBody] SysPatient post)
        {
            try
            {
                if (post.Phone.IsNullOrWhiteSpace())
                {
                    throw new ArgumentException("手机号码不能为空");
                }

                if (post.IdCardNo.IsNullOrWhiteSpace())
                {
                    throw new ArgumentException("身份证号码不能为空");
                }
                var data = await _hisUserService.Reg(post);
                if (data.Code == 200)
                {
                    this.Logger($"创建用户. 请求数据:{data.Request}, 返回数据:{data.Response}", ActionLogTypesEnum.Debug);
                    var patient = await DC.Set<SysPatient>()
                        .FirstOrDefaultAsync(e => e.IdCardNo == data.Data.IdCardNo);
                    if (patient == null)
                    {
                        patient = new SysPatient();
                        patient.CopyPropertyFrom(data.Data);
                        patient.LastTime = DateTime.Now;
                        await DC.Set<SysPatient>().AddAsync(patient);
                        await DC.SaveChangesAsync();
                    }
                    return new Result<SysPatient>()
                    {
                        Data = patient
                    };
                }
                else
                {
                    this.Logger($"创建用户失败, 请求数据:{data.Request}, 返回数据:{data.Response}", ActionLogTypesEnum.Exception);
                    return new Result<SysPatient>()
                    {
                        Code = 1,
                        Message = data.Message ?? "创建用户失败"
                    };
                }
            }
            catch (Exception e)
            {
                this.Logger($"建档异常, {e.Message} | 用户信息[{JsonSerializer.Serialize(post)}] | 异常信息:{e.StackTrace}", ActionLogTypesEnum.Exception);
                return new Result<SysPatient>()
                {
                    Code = 1,
                    Message = $"建档失败, {e.Message}"
                };
            }
        }
    }
}
